import React, { useState, useEffect } from "react";
import {
  Form,
  Input,
  Modal,
  Card,
  Button,
  Table,
  Popconfirm,
  message,
  Upload,
} from "antd";
import {
  LoadingOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
} from "@ant-design/icons";
import {
  ProductCategoriesAPI,
  addAPI,
  delAPI,
  changeAPI,
} from "../service/productCategories";
import { dalImgUrl } from "../utils/tools";

function ProductList() {
  const columns = [
    {
      title: "序号",
      render(text, record, index) {
        return <>{index + 1}</>;
      },
      align: "center",
    },
    {
      title: "名字",
      dataIndex: "name",
      align: "center",
    },
    {
      title: "描述",
      align: "center",
    },
    {
      title: "主图",
      align: "center",
      render(text, record, index) {
        return (
          <img src={dalImgUrl(record.coverImg)} style={{ width: "3rem" }}></img>
        );
      },
    },
    {
      title: "操作",
      align: "center",
      render(text, record, index) {
        return (
          <>
            <Button
              type="primary"
              icon={<EditOutlined />}
              onClick={() => {
                setIsModalVisible(true);
                form.setFieldsValue({
                  name: record.name,
                });
                setCurrentId(record._id);
                setImageUrl(record.coverImg);
              }}
            ></Button>
            <Popconfirm
              title="确认删除此项吗?"
              onConfirm={(e) => {
                console.log(e);
                message.success("Click on Yes");
                delAPI(record._id).then(() => {
                  loadData();
                });
              }}
              onCancel={(e) => {
                console.log(e);
                message.error("Click on No");
              }}
              okText="确认"
              cancelText="取消"
            >
              <Button
                type="primary"
                style={{ marginLeft: "1rem" }}
                icon={<DeleteOutlined />}
                danger
              ></Button>
            </Popconfirm>
          </>
        );
      },
    },
  ];
  const [list, setList] = useState([]);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState("");
  const [currentId, setCurrentId] = useState("");
  const [total, setTotal] = useState(0);
  //modal
  const showModal = () => {
    setIsModalVisible(true);
  };

  const handleOk = () => {
    setIsModalVisible(false);
  };

  const handleCancel = () => {
    setIsModalVisible(false);
  };
  //form
  const onFinish = (values) => {
    console.log("Success:", values);
    saveHandle(values);
    setLoading(false);
    setCurrentId("");
  };

  const onFinishFailed = (errorInfo) => {
    console.log("Failed:", errorInfo);
  };
  //加载数据
  const loadData = async (page = 1) => {
    const res = await ProductCategoriesAPI({ page });
    console.log(res);
    setList(res.categories);
    setTotal(res.totalCount);
  };
  useEffect(() => {
    loadData();
  }, []);
  //添加数据
  const saveHandle = (val) => {
    if (currentId) {
      changeAPI(currentId, { ...val, ...{ coverImg: imageUrl } }).then(() => {
        setIsModalVisible(false);
        loadData();
      });
    } else {
      addAPI({ ...val, ...{ coverImg: imageUrl } }).then(() => {
        setIsModalVisible(false);
        loadData();
      });
    }
  };
  //上传文件
  const handleChange = (info) => {
    if (info.file.status === "uploading") {
      setLoading(true);

      return;
    }
    if (info.file.status === "done") {
      // Get this url from response in real world.
      console.log(info);
      setImageUrl(info.file.response.info);
    }
  };
  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  );
  return (
    <Card
      className="card"
      bordered
      title="商品列表"
      extra={
        <Button
          type="primary"
          onClick={() => {
            form.setFieldsValue({
              name: "",
            });
            setImageUrl("");
            showModal();
          }}
          icon={<PlusOutlined></PlusOutlined>}
        ></Button>
      }
      style={{ width: 800 }}
    >
      <Table
        rowKey="_id"
        columns={columns}
        dataSource={list}
        pagination={{
          total,
          pageSize: 10,
          onChange(page) {
            loadData(page);
          },
        }}
      />
      <Modal
        footer={null}
        title="编辑"
        visible={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form
          form={form}
          name="basic"
          initialValues={{ remember: true }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
        >
          <Form.Item
            label="名字"
            name="name"
            rules={[{ required: true, message: "请输入商品名字!" }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="主图"
            rules={[{ required: true, message: "请上传商品图片!" }]}
          >
            <Upload
              name="file"
              listType="picture-card"
              className="avatar-uploader"
              showUploadList={false}
              action="http://localhost:3009/api/v1/common/file_upload"
              onChange={handleChange}
            >
              {imageUrl ? (
                <img
                  src={dalImgUrl(imageUrl)}
                  alt="avatar"
                  style={{ width: "100%" }}
                />
              ) : (
                uploadButton
              )}
            </Upload>
          </Form.Item>

          <Form.Item>
            <Button block type="primary" htmlType="submit">
              保存
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </Card>
  );
}

export default ProductList;
